package org.javaboy.demo.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.FlashMap;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.SessionFlashMapManager;

@Controller
public class HelloController2 {

    @GetMapping("/hello2")
    public String hello(@RequestParam(value = "name",required = false) String name, HttpServletRequest request) {
        FlashMap flashMap = (FlashMap) request.getAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE);
        flashMap.put("name", name);
        //重定向到 /hello3
        return "redirect:/hello3";
    }

    @GetMapping("/hello3")
    @ResponseBody
    public String hello3(Model model) {
        Object name = model.getAttribute("name");
        System.out.println("name = " + name);
        return "hello3";
    }

    @GetMapping("/hello4")
    public String hello4(@RequestParam("name") String name, RedirectAttributes attrs) {
        attrs.addFlashAttribute("name", name);
        return "redirect:/hello3";
    }

}
